﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Odyssey.Utils
{
    public static class PerspectiveCorrection
    {
        public static void AdjustPerspective(this FrameworkElement element, FrameworkElement anchestor, bool verticalOnly = false)
        {

            if (anchestor.ActualHeight != 0.0)
            {

                PlaneProjection projection = new PlaneProjection();
                TranslateTransform translate = new TranslateTransform();
                element.Projection = projection;
                element.RenderTransform = translate;

                GeneralTransform gt = element.TransformToVisual(anchestor);
                Point pt;
                if (gt.TryTransform(new Point(), out pt))
                {
                    double ew = element.ActualWidth;
                    double eh = element.ActualHeight;

                    double dx = (anchestor.ActualWidth - ew) / 2 - pt.X;
                    double dy = (anchestor.ActualHeight - eh) / 2 - pt.Y;

                    double w = Math.Max(ew, pt.X);
                    double h = Math.Max(eh, pt.Y);

                    if (w > 0 && verticalOnly) projection.CenterOfRotationX = -pt.X / w; else projection.CenterOfRotationX = 0.0;
                    //                if (h > 0) projection.CenterOfRotationY = -pt.Y / h; else projection.CenterOfRotationY = 0.0;


                    translate.X = dx;
                    projection.GlobalOffsetX = -dx;

                    translate.Y = dy;
                    projection.GlobalOffsetY = -dy;
                }
            }
        }
    }
}
